<template>
  <view>
    <wd-popup
      :model-value="show"
      :custom-style="popupStyle"
      safe-area-inset-bottom
      position="bottom"
      transition="slide-up"
      @update:model-value="$emit('update:show', $event)"
    >
      <view class="close-button" @click="$emit('update:show', false)">
        <wd-icon name="close" size="36rpx" color="#333333" />
      </view>
      <template v-if="currentProduct">
        <view class="header">
          <v-image
            height="110rpx"
            width="110rpx"
            border-radius="16rpx"
            :src="
              product.sku_type === 'SINGLE'
                ? product.image
                : currentProduct?.image
            "
            mode="aspectFill"
          />
          <view class="product-price">
            <view class="label">
              到手价
            </view>
            <v-price
              size="56rpx"
              sign-size="30rpx"
              :price="currentProduct.sell_price"
              :keep-decimal="false"
            />
            <view v-if="currentProduct.market_price" class="market-price">
              {{ `¥${currentProduct.market_price.toFixed(2)}` }}
            </view>
          </view>
        </view>
        <scroll-view scroll-y style="flex: 1; height: 0">
          <view class="product-select-block">
            <view class="address-item" @click="userStore.getAddress">
              <template v-if="userAddress">
                <v-icon
                  size="44rpx"
                  src="@/static/icons/product-select-address.svg"
                />
                <view class="address-content">
                  <view class="address-main">
                    {{ userAddress.detailInfo }}
                  </view>
                  <view class="address-sub">
                    <text v-if="userAddress.userName">
                      {{ userAddress.userName }}
                    </text>
                    <text v-if="userAddress.telNumber">
                      {{ userAddress.telNumber }}
                    </text>
                  </view>
                </view>
              </template>
              <template v-else>
                <!-- #ifdef MP-ALIPAY -->
                <v-icon size="44rpx" src="@/static/images/alipay-icon.png" />
                <view class="alipay-holder">
                  支付宝地址导入
                </view>
                <!-- #endif -->
              </template>
              <wd-icon name="arrow-right" size="24rpx" color="#999999" />
            </view>
          </view>
          <view class="product-select-block" style="gap: 24rpx">
            <view
              v-for="(spec, index) in displaySpecList"
              :key="index"
              class="spec-group"
            >
              <view class="spec-title">
                {{ spec.name }}
              </view>
              <view class="spec-list">
                <view
                  v-for="(specValue, valueIndex) in spec.valueList"
                  :key="valueIndex"
                  class="spec-item"
                  :class="{
                    active: specValue.selecting,
                    'sold-out': specValue.soldOut
                  }"
                  @click="selectSpec(spec.name, specValue.value)"
                >
                  <view class="text">
                    {{ specValue.value }}
                  </view>
                </view>
              </view>
            </view>
            <view class="product-select-item">
              <view class="label">
                购买数量
              </view>
              <view
                v-if="
                  product?.quota_type === 'QUOTA' &&
                    product?.quota_purchase_rule?.marketing_text
                "
                class="purchase-rule"
              >
                {{ product.quota_purchase_rule.marketing_text }}
              </view>
              <view class="content">
                <v-input-number
                  v-model="quantity"
                  action
                  :precision="0"
                  :min="1"
                  :max="maxQuantity"
                />
              </view>
            </view>
            <view class="product-select-item" @click="showRemark">
              <view class="label">
                订单备注
              </view>
              <view class="content">
                <view class="remark" :class="{ placeholder: !remark }">
                  {{ remark || '无备注' }}
                </view>
                <wd-icon name="arrow-right" size="24rpx" color="#999999" />
              </view>
            </view>
          </view>
          <view class="product-select-block">
            <view class="shipping-item">
              <v-icon
                size="44rpx"
                src="@/static/icons/product-select-shipping.svg"
              />
              <view class="main">
                运费
              </view>
              <view class="sub">
                {{ shippingText }}
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="submit-button-container">
          <v-button
            type="primary"
            :disabled="!!disabledText"
            @click="buyImmediatelyHandle"
          >
            {{ disabledText ? disabledText : '立即下单' }}
          </v-button>
        </view>
      </template>
      <template v-else>
        <v-loading-block />
      </template>
    </wd-popup>
    <m-textarea-popup
      v-model="editingRemark"
      v-model:show="isShowRemarkPopup"
      title="订单备注"
      edit
      @submit="sumitRemarkHandle"
    />
  </view>
</template>

<script setup lang="ts">
const popupStyle = computed(() => {
  const list: string[] = [];
  list.push('padding-top:24rpx');
  list.push('background:#f5f6fa');
  // #ifdef MP-ALIPAY
  list.push('max-height:65vh');
  // #endif
  // #ifndef MP-ALIPAY
  list.push('height:65vh');
  // #endif
  list.push('display:flex');
  list.push('flex-direction:column');
  list.push('border-radius: 16rpx 16rpx 0 0');
  return list.join(';');
});

const props = defineProps<{
  show: boolean;
  product: SpuVO;
  skuInfo?: SkuVO;
}>();

const emits = defineEmits<{
  'update:show': [val: boolean];
}>();

const product = toRef(props, 'product');
const selectingSpec = ref<{ name: string; value: string }[]>([]);
const selectSpec = (name: string, value: string) => {
  const newList = selectingSpec.value.concat([]);
  const index = newList.findIndex((spec) => spec.name === name);
  if (index >= 0) {
    newList.splice(index, 1, { name, value });
  } else {
    newList.push({ name, value });
  }
  const list = product.value?.sku_list;
  // 直接有这个sku
  const target = list.find((sku) =>
    sku.spec_info.every((skuSpec) =>
      newList.some(
        (selectingSpec) =>
          selectingSpec.name === skuSpec.name &&
          selectingSpec.value === skuSpec.value
      )
    )
  );
  if (target) {
    selectingSpec.value = newList;
    if (quantity.value > target.inventory) {
      quantity.value = target.inventory || 1;
    }
    return;
  }
  // 没有这个sku，尝试找一个有该规格的
  const secondTarget = list.find((sku) =>
    sku.spec_info.some(
      (skuSpec) => skuSpec.name === name && skuSpec.value === value
    )
  );
  if (secondTarget) {
    selectingSpec.value = secondTarget.spec_info.map((spec) => ({
      name: spec.name,
      value: spec.value
    }));
  } else {
    // 没有有这个规格的sku，无效按钮
  }
};
const initDefaultSelectingSpec = () => {
  const bestChooce = product.value?.sku_list.find((sku) => !!sku.def_sku_flag);
  if (bestChooce) {
    selectingSpec.value = bestChooce.spec_info.map((spec) => ({
      name: spec.name,
      value: spec.value
    }));
    return;
  }
  const firstChoose = product.value?.sku_list[0];
  if (firstChoose) {
    selectingSpec.value = firstChoose.spec_info.map((spec) => ({
      name: spec.name,
      value: spec.value
    }));
  }
};
watch(
  () => props.show,
  (val) => {
    if (val) {
      remark.value = '';
      initDefaultSelectingSpec();
      if (props.skuInfo) {
        selectingSpec.value = props.skuInfo.spec_info.map((spec) => ({
          name: spec.name,
          value: spec.value
        }));
      }
    }
  }
);

const checkSkuInventory = (target: { name: string; value: string }[]) => {
  const item = product.value?.sku_list.find((sku) =>
    sku.spec_info.every((skuSpec) =>
      target.some(
        (selectingSpec) =>
          selectingSpec.name === skuSpec.name &&
          selectingSpec.value === skuSpec.value
      )
    )
  );
  return !!item && item.sale_status && item.inventory > 0;
};
const displaySpecList = computed(() => {
  if (!product.value?.spec_info) return [];
  const list: {
    name: string;
    valueList: { value: string; selecting: boolean; soldOut: boolean }[];
  }[] = [];
  const lastIndex = selectingSpec.value.length - 1;
  for (let i = 0; i < product.value.spec_info.length; i += 1) {
    const spec = product.value.spec_info[i];
    const rest = selectingSpec.value.filter(
      (selecting) => selecting.name !== spec.name
    );
    list.push({
      name: spec.name,
      valueList: spec.value_list.map((value) => ({
        value,
        selecting: selectingSpec.value.some(
          (selecting) =>
            selecting.name === spec.name && selecting.value === value
        ),
        soldOut:
          i === lastIndex &&
          !checkSkuInventory([...rest, { name: spec.name, value }])
      }))
    });
  }
  return list;
});
const currentProduct = computed(() => {
  if (!product.value?.sku_list) return undefined;
  const sku = product.value.sku_list.find((sku) =>
    sku.spec_info.every((skuSpec) =>
      selectingSpec.value.some(
        (selectingSpec) =>
          selectingSpec.name === skuSpec.name &&
          selectingSpec.value === skuSpec.value
      )
    )
  );
  return sku;
});

const shippingText = computed(() => {
  if (!currentProduct.value) return '-';
  if (userAddress.value === undefined) return '选择地址后展示';
  if (shippingFee.value === undefined) return '-';
  if (shippingFee.value === -1) return '该地区无法配送';
  if (shippingFee.value === 0) return '包邮';
  return `¥${shippingFee.value.toFixed(2)}`;
});
const shippingFee = ref<number>();
const getShippingInfo = async () => {
  if (!currentProduct.value) return;
  // 没库存查了会报错
  if (!currentProduct.value.inventory || !currentProduct.value.sale_status) {
    shippingFee.value = undefined;
    return;
  }
  shippingFee.value = undefined;
  const response = await $api.postOrderSubmitTrial(
    {
      order_req: [
        {
          sku_id: currentProduct.value.id,
          quantity: quantity.value,
          discount_type: 'NONE',
          landing_page_id: ''
        }
      ],
      recipient_info: userStore.getRecipientInfo()
    },
    {
      ignoreApiCodes: [700003]
    }
  );
  switch (response.__error) {
    case undefined: {
      if (response.code === 700003) {
        shippingFee.value = undefined;
      } else {
        const item = response.data.list[0];
        const fee = item?.shipping_fee ?? -1;
        shippingFee.value = fee;
      }
    }
  }
};

const userStore = $store.user();
const userAddress = computed(() => userStore.userAddress);
const quantity = ref(1);
const maxQuantity = computed(() => {
  if (!currentProduct.value || !product.value) return undefined;
  const inventory = currentProduct.value.inventory;
  if (product.value.quota_type === 'NO_QUOTA') return inventory;
  const maxPerBuy = product.value.quota_purchase_rule?.max_per_buy;
  return maxPerBuy ? Math.min(inventory, maxPerBuy) : inventory;
});
watch(
  () =>
    [userStore.userAddress?._t, currentProduct.value, quantity.value] as const,
  (val) => {
    if (val[0] && val[1]) getShippingInfo();
  },
  { immediate: true }
);
const remark = ref('');
const editingRemark = ref('');
const isShowRemarkPopup = ref(false);
const showRemark = () => {
  editingRemark.value = remark.value;
  isShowRemarkPopup.value = true;
};
const sumitRemarkHandle = () => {
  remark.value = editingRemark.value;
  isShowRemarkPopup.value = false;
};

const disabledText = computed(() => {
  if (!currentProduct.value) return '无效商品';
  if (!currentProduct.value.inventory) return '无库存';
  if (!currentProduct.value.sale_status) return '无库存';
  if (currentProduct.value.inventory < quantity.value) return '库存不足';
  if (userAddress.value === undefined) return '请选择地址';
  if (shippingFee.value === undefined) return '运费计算中 请稍后';
  return '';
});

const getDetails = async (data: PostOrderSubmitDetailData) => {
  uni.showLoading({ mask: true });
  const response = await $api.postOrderSubmitDetail(data, {
    ignoreApiCodes: [700003]
  });
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      if (response.code === 700003) {
        uni.showToast({ title: response.msg, icon: 'none' });
      } else {
        return response.data.list;
      }
  }
};
const buyImmediatelyHandle = async () => {
  if (!currentProduct.value) return;
  const checkedList = await getDetails([
    {
      sku_id: currentProduct.value.id,
      quantity: quantity.value,
      discount_type: 'NONE',
      landing_page_id: ''
    }
  ]);
  if (!checkedList) return;
  const pageStore = $store.page();
  pageStore.setParameters({ list: checkedList, remark: remark.value });
  uni.navigateTo({ url: '/pages/order/order-confirm?type=order' });
  emits('update:show', false);
};
</script>

<style lang="scss" scoped>
.close-button {
  position: absolute;
  top: 36rpx;
  right: 36rpx;
  z-index: 1;
}

.header {
  display: flex;
  align-items: center;
  margin: 0 24rpx 24rpx;
  gap: 24rpx;
  .product-price {
    display: flex;
    align-items: baseline;
    gap: 0 8rpx;
    margin-top: 30rpx;
    white-space: nowrap;
    .label {
      color: #ff2f3b;
      flex-shrink: 0;
    }
    .market-price {
      color: #999999;
      text-decoration: line-through;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      white-space: nowrap;
    }
  }
}

.product-select-block {
  margin: 0 24rpx 24rpx;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 12rpx;
  .address-item {
    display: flex;
    align-items: center;
    gap: 24rpx;
    .address-content {
      flex: 1;
      min-width: 0;
      .address-main {
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
      }
      .address-sub {
        color: #999999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        display: inline-flex;
        gap: 0 8rpx;
      }
    }
    .alipay-holder {
      color: #007afe;
      flex: 1;
      min-width: 0;
    }
    .weixin-holder {
      color: #07c160;
    }
  }

  .spec-group {
    margin-bottom: 12rpx;
    .spec-title {
      font-weight: bold;
      margin-bottom: 24rpx;
    }
    .spec-list {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx 24rpx;
      .spec-item {
        position: relative;
        max-width: calc(100% - 50rpx);
        box-sizing: border-box;
        line-height: 60rpx;
        border: 1px solid #f5f6fa;
        background-color: #f5f6fa;
        border-radius: 16rpx;
        padding: 0 24rpx;
        transition:
          border 0.3s,
          background-color 0.3s,
          color 0.3s;
        .text {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: break-all;
        }
        &.active {
          border: 1px solid #ff2f3b;
          background-color: rgba(255, 47, 59, 0.1);
          .text {
            color: #ff2f3b;
          }
        }
        &.sold-out {
          border: 1px solid rgba(245, 246, 250, 0.5);
          background-color: rgba(245, 246, 250, 0.5);
          .text {
            color: rgba(51, 51, 51, 0.5);
          }
          &::after {
            content: '售罄';
            position: absolute;
            z-index: 1;
            right: 0;
            top: 0;
            transform: translate(80%, -50%);
            background-color: #cccccc;
            border-radius: 18rpx 18rpx 18rpx 0;
            height: 36rpx;
            width: 80rpx;
            font-size: 24rpx;
            line-height: 36rpx;
            color: white;
            font-weight: 300;
            text-align: center;
          }
        }
        &.sold-out.active {
          border: 1px solid #cccccc;
        }
      }
    }
  }

  .product-select-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;
    .label {
      font-weight: bold;
      flex-shrink: 0;
    }
    .purchase-rule {
      color: #ff2f3b;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
    }
    .content {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12rpx;
      .remark {
        flex: 1;
        min-width: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        text-align: right;
        &.placeholder {
          color: #999999;
          font-weight: 300;
        }
      }
    }
  }

  .shipping-item {
    display: flex;
    align-items: center;
    gap: 24rpx;
    .main {
      font-weight: bold;
      flex: 1;
      min-width: 0;
    }
    .sub {
      color: #999999;
    }
  }
}

.submit-button-container {
  margin: 0 24rpx 24rpx;
  padding: 10rpx 0;
}
</style>
